from django.shortcuts import render,redirect

# Create your views here.
from book.models import AuthorModels,BookModels
from django.http import JsonResponse,HttpResponse
def show(request):
    if request.method == 'GET':

        book_data=BookModels.objects.all()

        return render(request,'show.html',locals())



def add(request):
     if request.method=='GET':
         data_author=AuthorModels.objects.all()
         return render(request,'add.html',locals())
     elif request.method=='POST':
        print(request.POST)
        ret=BookModels.objects.create(
            name=request.POST.get('name'),
            price=request.POST['price'],
            counts=request.POST['counts'],
            author_id=request.POST['author']
        )
        return redirect('/book/show/')



def add2(request):
    if request.method=="GET":
        data_author = AuthorModels.objects.all()
        return render(request,'add2.html',locals())
    elif request.method=='POST':
        print(request.POST.getlist('counts'))

        au=AuthorModels.objects.get(id=request.POST.get('author'))
        ret=BookModels.objects.create(
            name=request.POST.get('book'),
            price=request.POST.get('price'),
            counts=request.POST.getlist('counts')[0],
            author=au
            # author_id=request.POST['author']

        )
        return redirect('/book/show/')


def content(request):
    data={'msg':'ok','data':[{'id':'1','username':'张三'},{'id':'2','username':'李四'}]}

    return JsonResponse(data)


from django.views import View

class Demo2(View):
    def get(self,reqeust):
        return HttpResponse('get请求')
    def post(self,request):
        return  HttpResponse('post请求')
